package cn.wawi.utils;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;

/**
 * @description 字符串工具类
 * @author 龚亮
 * @date 2014-10-15 15:11:24
 */
public class StringUtil extends StringUtils {

	public static void main(String[] args) {
		System.out.println(generateRandomDir("asflkj.jpg"));
		System.out.println(subFileName("adsad.apk"));
	}

	/**
	 * 截取文件后缀
	 */
	public static String subFileName(String fileName) {
		int index = fileName.lastIndexOf(".");
		return -1 == index ? fileName : fileName.substring(index + 1);
	}

	/**
	 * 正则表达式获取xml指定值
	 */
	public static String getXml(String html, String attr) {
		String result = "";
		Pattern p = Pattern.compile("<" + attr + ">([^</]+)</" + attr + ">");// 正则表达式
		Matcher m = p.matcher(html);
		while (m.find()) {
			result = m.group(1);
		}
		return result;
	}

	/**
	 * 正则表达式获取xml指定值
	 */
	public static List<String> getXmlList(String html, String attr) {
		List<String> result = new ArrayList<String>();
		Pattern p = Pattern.compile("<" + attr + ">([^</]+)</" + attr + ">");// 正则表达式
		Matcher m = p.matcher(html);
		while (m.find()) {
			result.add(m.group(1));
		}
		return result;
	}

	/**
	 * 获取随机uuid文件名
	 */
	public static String generateRandonFileName(String filename) {
		//return UUID.randomUUID().toString() + "$" + filename;
		return DateUtil.getDate("yyyyMMddHHmmss") + "$" + filename;
	}

	/**
	 * 获得hashcode生成二级目录
	 */
	public static String generateRandomDir(String uuidFileName) {
		int hashCode = uuidFileName.hashCode();
		// 一级目录
		int d1 = hashCode & 0xf;
		// 二级目录
		int d2 = (hashCode >> 4) & 0xf;
		return "/" + d1 + "/" + d2;
	}

	/**
	 * 获得日期生成二级目录
	 */
	public static String generateRandomDateDir() {
		return DateUtil.getYear() + "/" + DateUtil.getMonth() + "/" + DateUtil.getDay() + "/";
	}

	/**
	 * 首字母小写
	 */
	public static String firstCharToLowerCase(String str) {
		char firstChar = str.charAt(0);
		if ((firstChar >= 'A') && (firstChar <= 'Z')) {
			char[] arr = str.toCharArray();
			int tmp25_24 = 0;
			char[] tmp25_23 = arr;
			tmp25_23[tmp25_24] = (char) (tmp25_23[tmp25_24] + ' ');
			return new String(arr);
		}
		return str;
	}

	/**
	 * 首字母大写
	 */
	public static String firstCharToUpperCase(String str) {
		char firstChar = str.charAt(0);
		if ((firstChar >= 'a') && (firstChar <= 'z')) {
			char[] arr = str.toCharArray();
			int tmp25_24 = 0;
			char[] tmp25_23 = arr;
			tmp25_23[tmp25_24] = (char) (tmp25_23[tmp25_24] - ' ');
			return new String(arr);
		}
		return str;
	}

	/**
	 * 是否全为大写字母
	 */
	public static boolean isAllUpperCase(String str) {
		boolean flag = true;
		for (int i = 0; i < str.length(); i++) {
			char firstChar = str.charAt(i);
			if ((firstChar >= 'a') && (firstChar <= 'z')) {
				flag = false;
			}
		}
		return flag;
	}

	/**
	 * str是否为null/""
	 */
	public static boolean isBlank(String str) {
		return ((str == null) || ("".equals(str.trim())));
	}

	/**
	 * str是不为null/""
	 */
	public static boolean notBlank(String str) {
		return ((str != null) && (!("".equals(str.trim()))));
	}

	/**
	 * str[]是不为null/""
	 */
	public static boolean notBlank(String[] strings) {
		if (strings == null)
			return false;
		for (String str : strings)
			if ((str == null) || ("".equals(str.trim())))
				return false;
		return true;
	}

	/**
	 * object[]不为null
	 */
	public static boolean notNull(Object[] paras) {
		if (paras == null)
			return false;
		for (Object obj : paras)
			if (obj == null)
				return false;
		return true;
	}

	/**
	 * List不为null
	 */
	public static boolean notNull(List<?> paras) {
		if (paras == null || paras.size() == 0)
			return false;
		for (Object obj : paras)
			if (obj == null)
				return false;
		return true;
	}

	/**
	 * 空
	 */
	public static boolean isEmpty(String str) {
		return str == null || str.length() == 0;
	}

	/**
	 * 非空
	 */
	public static boolean isNotEmpty(String str) {
		return !isEmpty(str);
	}

	/**
	 * 将驼峰风格替换为下划线风格
	 */
	public static String camelhumpToUnderline(String str) {
		final int size;
		final char[] chars;
		final StringBuilder sb = new StringBuilder((size = (chars = str.toCharArray()).length) * 3 / 2 + 1);
		char c;
		for (int i = 0; i < size; i++) {
			c = chars[i];
			if (isUppercaseAlpha(c)) {
				sb.append('_').append(toLowerAscii(c));
			} else {
				sb.append(toUpperAscii(c));
			}
		}
		return sb.charAt(0) == '_' ? sb.substring(1) : sb.toString();
	}

	/**
	 * 将下划线风格替换为驼峰风格
	 */
	public static String underlineToCamelhump(String str) {
		Matcher matcher = Pattern.compile("_[a-z]").matcher(str);
		StringBuilder builder = new StringBuilder(str);
		for (int i = 0; matcher.find(); i++) {
			builder.replace(matcher.start() - i, matcher.end() - i, matcher.group().substring(1).toUpperCase());
		}
		if (Character.isUpperCase(builder.charAt(0))) {
			builder.replace(0, 1, String.valueOf(Character.toLowerCase(builder.charAt(0))));
		}
		return builder.toString();
	}

	public static boolean isUppercaseAlpha(char c) {
		return (c >= 'A') && (c <= 'Z');
	}

	public static boolean isLowercaseAlpha(char c) {
		return (c >= 'a') && (c <= 'z');
	}

	public static char toUpperAscii(char c) {
		if (isUppercaseAlpha(c)) {
			c -= (char) 0x20;
		}
		return c;
	}

	public static char toLowerAscii(char c) {
		if (isUppercaseAlpha(c)) {
			c += (char) 0x20;
		}
		return c;
	}

	/**
	 * 判断字符串是否全为中文
	 */
	public static boolean isChinese(String str) {
		return str.matches("[\\u4E00-\\u9FA5]+");
	}

	/**
	 * 获取项目名
	 */
	public static String getRootPath() {
		String str = System.getProperty("user.dir");
		return "/" + str.substring(str.lastIndexOf("\\") + 1);
	}

	/**
	 * 获取客户端IP
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ipAddress = request.getHeader("x-forwarded-for");
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getRemoteAddr();
			if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
				// 根据网卡取本机配置的IP
				InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
				ipAddress = inet.getHostAddress();
			}
		}
		// 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
		if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
															// = 15
			if (ipAddress.indexOf(",") > 0) {
				ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
			}
		}
		return ipAddress;
	}
}
